/**
 * Created by huachuan on 2016/1/16.
 */
angular.module('mehomecontrollers', [])
  //我的收藏的Controller
  .controller('MeHomeCtrl', function($scope,$rootScope,$ionicPopup,$ionicActionSheet,$cordovaStatusbar,$cordovaFileTransfer,$state,Home,ENV,Loading,Toast,Storage,History,ShareServiceOther,ShareService) {
      //获取会员编号
      var memberId = '';
      $scope.picPath = ENV.picPath;
    $scope.isShareShow = ShareService.getIsShowShareWindow();//判断是否显示分享框
      $scope.homeList = [];
      var isFirstIn = true;
      $scope.$on('$ionicView.beforeEnter', function () {
        memberId = Storage.get("member").member_id;
        if(isFirstIn){
          Loading.showLoading();
          isFirstIn = false;
        }
        Home.getMeHomeList(memberId);
        //当页面不是第一次进入的时候，重新加载酒窝的点赞状态，收藏状态，评论数
        if($scope.homeList!=undefined && $scope.homeList.length!=0){
          searchList = [];
          for(i=0;i<$scope.homeList.length;i++){
            search = {
              mh_id:$scope.homeList[i].mh_id,
              member_id:memberId
            }
            searchList.push(search);
          }
          Home.getCurrentHomeInfo(searchList);//获取
        }
      })
    //局部刷新酒窝的点赞信息
    $scope.$on('Home.currentHomeInfoeUpdated',function(){
      var result = Home.getCurrentJson().currentInfo;
      for(i=0;i<result.length;i++){
        for(j=0;j<$scope.homeList.length;j++){
          if(result[i].mh_id==$scope.homeList[j].mh_id){
            $scope.homeList[j].lhomeStatus = result[i].lhomeStatus;
            $scope.homeList[j].mchomeStatus = result[i].mchomeStatus;
            $scope.homeList[j].mh_comment_num = result[i].mh_comment_num;
            $scope.homeList[j].mh_praise_num = result[i].mh_praise_num;
          }
        }
      }
    });
    $scope.$on('Home.meHomeListUpdated',function(){
      $scope.$broadcast('scroll.refreshComplete');
      $scope.homeList = Home.getMeHomeListJson();
      $scope.member = Home.getMemberInfo();
      Loading.hideLoading();
    });
    //下拉刷新
    $scope.doRefresh = function(){
      Home.getMeHomeList(memberId);
    }
    //加载更多酒窝信息
    $scope.loadMore = function(){
        Home.getMoreMeHomeList(memberId);
    }
    $scope.hasNextPage = function(){
      return Home.meHomeHasNextPage();
    }
    $scope.$on('Home.MoreMeHomeListUpdated',function(){
      $scope.$broadcast('scroll.infiniteScrollComplete');
      $scope.homeList = Home.getMeHomeListJson();
      console.log($scope.homeList.length);
    });

    //点击用户头像是的操作
    $scope.go2OtherHome  = function(otherMemberId){
      if(memberId==otherMemberId){
        $state.transitionTo("tab.meIndex");
      }else{
        $state.transitionTo("user-dimple-care-list",{memberId:otherMemberId});
      }
    }
    //酒窝显示大图
    $scope.showBigImage= function(homeIndex,picIndex){
      var items = [];
      var lookImageList = $scope.homeList[homeIndex].picSrc;
      var pswpElement = document.querySelectorAll('.pswp')[0];
      for(i=0;i<lookImageList.length;i++){
        var temp = {
          src:$scope.picPath+"big_"+lookImageList[i].src,
          w:lookImageList[i].w,
          h:lookImageList[i].h
        };
        items.push(temp);
      }
      var options = {
        index: picIndex,
        history: false,
        focus: false,
        loop: false,
        /*pinchToClose:false,
        closeOnVerticalDrag:false,*/
        showAnimationDuration: 100,
        hideAnimationDuration: 100,
        backButtonHideEnabled:true,
        captionAndToolbarFlipPosition:true,
        loadingIndicatorDelay:100
      };
      $rootScope.gallery  = new PhotoSwipe(pswpElement,PhotoSwipeUI_Default,items,options);
      $rootScope.gallery.init();
      //$cordovaStatusbar.hide();
    }
    $rootScope.downloadHomeImg = function(){
      var url = $rootScope.gallery.currItem.src;
      var timestamp=new Date().getTime();
      var targetPath = cordova.file.externalRootDirectory+"winelife/winelife_home_"+timestamp+".jpg";
      var trustHosts = true;
      var options = {};
      $ionicActionSheet.show({
       buttons: [
       {text: '保存到手机相册'}
       ],
       cancelText: '取消',
       buttonClicked: function (index) {
       if(index==0){
       $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
       .then(function(result) {
       Toast.showMessage("保存成功");
       }, function(err) {
           Toast.showMessage("保存成功");
       }, function (progress) {
       });
       }
       return true;
       }
       });
    }
    //单击缩小图片
    $rootScope.smallPicture = function(){
      $rootScope.gallery.close();
     // $cordovaStatusbar.show();
    }
    //收藏酒窝
    var collectorLikeHomeIndex = '';
    $scope.collectHome =function(index,mhId){
      Home.collectHome(memberId,mhId);
      collectorLikeHomeIndex = index;
    }
    $scope.$on('Home.collectHomeUpdated',function(){
      var result = Home.getCollectHomeMsgJson();
      Toast.showMessage(result.mchomeMsg);
      $scope.homeList[collectorLikeHomeIndex].mchomeStatus = result.mchomeStatus;
    });
    //点赞酒窝
    $scope.likeHome =function(index,mhId){
      Home.likeHome(memberId,mhId);
      collectorLikeHomeIndex = index;
    }
    $scope.$on('Home.likeHomeUpdated',function(){
      var result = Home.getLikeHomeMsgJson();
      Toast.showMessage(result.lhomeMsg);
      $scope.homeList[collectorLikeHomeIndex].lhomeStatus = result.lhomeStatus;
    });
    //删除酒窝
    $scope.showDeleteHome = false;
    var saveHomeIndex = '';
    $scope.deleteHome = function(homeIndex){
      $ionicPopup.confirm({
        template: '<p style="text-align: center;font-size:16px">确定要删除该酒窝吗？</p>',
        cancelText: '取消',
        okText: '确定',
        okType: 'hd-red-btn',
        cancelType: 'cancel-esc-btn'
      }).then(function (res) {
        if (res) {
          //删除对应的酒窝
          Loading.showLoading();
          //$scope.homeList[saveHomeIndex].mh_id 酒窝的编号
          Home.deleteHome(memberId,$scope.homeList[homeIndex].mh_id);
          saveHomeIndex = homeIndex;
        }
      });
      //saveHomeIndex = homeIndex;
      //$scope.showDeleteHome = true;
    }
    /*$scope.confirmDeleteHome = function(){
      Loading.showLoading();
      Home.deleteHome(memberId,$scope.homeList[saveHomeIndex].mh_id);
      $scope.showDeleteHome = false;
    }*/
    $scope.$on('Home.deleteHomeUpdated',function(){
      Loading.hideLoading();
      var result = Home.getDeleteHomeMsgJson();
      if(result.deleteHomeState){
        $scope.homeList.splice(saveHomeIndex,1);
      }
      Toast.showMessage(result.deleteHomeMsg);
    });

    //显示酒窝分享框
    $scope.showHomeShare = function(mh_id){
      ShareServiceOther.showShareWindow(mh_id,"home");
    };

    //返回
    $scope.goback = function(){History.goback()}

  });
